// @Author miaoqing
// @Date 2024/02/27 15:41:00
// @Desc
package logic

import (
	"core/command"
	"core/component/logger"
	"core/network"
	"sync"
)

type PvpClient struct {
	tcpClient  *network.TcpClient
	serverID   string
	serverAddr string
	onMsg      sync.Once
}

func (pc *PvpClient) registerPvpMsgHandler() {
	pc.tcpClient.Router.Register(uint16(command.Command_PvpForwardPacket_Server), pc.pvpForwardPacketHandler)
}

func (pc *PvpClient) checkConnect(srvAddr string) {
	if pc.tcpClient.IsRunning() {
		return
	}
	pc.connect(srvAddr)
}

func (pc *PvpClient) connect(addr string) {
	if err := pc.tcpClient.Connect(addr); err != nil {
		logger.Error("[连接] Online->Pvp连接失败")
		return
	}
	pc.onMsg.Do(pc.registerPvpMsgHandler)
	pc.msgToGateway()
	logger.Infof("[连接] Online->Pvp连接成功 SrvID:%v srvAddr:%v", pc.serverID, pc.serverAddr)
}

func (pc *PvpClient) msgToGateway() {
	msgSend := &command.RegisterToPvp{
		//Msgids:     pc.msgID,
		ServerID:   ServerInstance().id,
		ProcIndex:  uint32(ServerInstance().processIdx),
		ServerAddr: ServerInstance().httpAddr,
	}
	pc.sendMsg(command.Command_RegisterToPvp_Server, msgSend)
}

// OnCloseCallBack 连接断开回调
func (gc *PvpClient) OnCloseCallBack() {
	//WorldGetMe().chanGatewayDown <- gc.serverID
	logger.Debugf("[连接] Gateway服务器连接断开 地址:%v", gc.serverID)
}

// sendMsg 异步发送数据包 (发送消息包给gateway服务器)
func (hc *PvpClient) sendMsg(cmd command.Command, msg interface{}) bool {
	return hc.tcpClient.AsyncSend(uint16(cmd), msg)
}
